package FX;

import BasicClass.Bill;
import BasicClass.Book;
import BasicClass.Record;
import BasicClass.User;
import Connection.*;
import DAO.DaoException;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;


public class SettleUI {
    static User user;//当前登录用户
    static boolean FirstLoad = true;//初始载入标识
    static ArrayList<Book> books;//需操作的书籍列表
    static ArrayList<User> accounts;//需操作的账户列表
    static ArrayList<Bill> bills;//需操作的账户列表
    static ArrayList<Record> records;//需操作的借阅记录列表
    public String name;//当前界面的名称
    static BookDaoImpl bookDao;//数据库连接DAO层
    static RecordDaoImpl recordDao;
    static BillDaoImpl billDao;
    static AccountDaoImpl userDao;
    static TableView<Book> tableViewBook;//当前界面的展示数据表
    static TableView<User> tableViewAccount;
    static TableView<Bill> tableViewBill;
    static TableView<Record> tableViewRecord;
    public int choose;//传递的参数选择值
    public SettleUI(ArrayList arrayList, String name, int choose){
        //结算界面的参数传递
        switch (choose){
            case 1:
            case 3:
            case 6:
            case 9:
                books = arrayList;break;
            case 2:
                records = arrayList;break;
            case 5:
            case 8:
                bills = arrayList;break;
            case 7:
                accounts = arrayList;break;
            default:
        }
        this.name = name;
        this.choose=choose;
        MyConnection Connection = ManagerUI.getMyConnection();
        bookDao = new BookDaoImpl(Connection);
        recordDao = new RecordDaoImpl(Connection);
        billDao = new BillDaoImpl(Connection);
        userDao = new AccountDaoImpl(Connection);
        user = ManagerUI.getUser();
    }

    public void display() {
        //计算界面布局展示
        FirstLoad = false;
        Stage settlement = new Stage();
        VBox Layout = new VBox();
        Scene scene = new Scene(Layout, 1200, 450);

        HBox ButtonBox = new HBox();
        Button Back = new Button("返回");
        Button Initial = new Button("初始");
        Button Change = new Button("修改");
        Button Delete = new Button("删除");
        Button Confirm = new Button("确定");
        Button Cancel = new Button("清空");
        ButtonBox.setSpacing(10);
        ButtonBox.setAlignment(Pos.CENTER);
        //表单声明
        tableViewBook = new TableView<>();
        tableViewAccount = new TableView<>();
        tableViewBill = new TableView<>();
        tableViewRecord = new TableView<>();
        AtomicInteger command = new AtomicInteger(0);//操作标识
        switch (choose) {
            case 1:
            case 3:
            case 6:
            case 9:
                TableColumn ISBN = new TableColumn("ISBN号");
                TableColumn Name = new TableColumn("书名");
                TableColumn Author = new TableColumn("作者");
                TableColumn Press = new TableColumn("出版社");
                TableColumn Price = new TableColumn("价格");
                TableColumn Number = new TableColumn("数目");
                TableColumn Location = new TableColumn("位置");
                TableColumn Label = new TableColumn("类型");
                TableColumn Remark = new TableColumn("备注");
                ISBN.setCellValueFactory(new PropertyValueFactory<>("ISBN"));
                Name.setCellValueFactory(new PropertyValueFactory<>("Name"));
                Author.setCellValueFactory(new PropertyValueFactory<>("Author"));
                Press.setCellValueFactory(new PropertyValueFactory<>("Press"));
                Price.setCellValueFactory(new PropertyValueFactory<>("Price"));
                Number.setCellValueFactory(new PropertyValueFactory<>("Number"));
                Location.setCellValueFactory(new PropertyValueFactory<>("Location"));
                Label.setCellValueFactory(new PropertyValueFactory<>("Label"));
                Remark.setCellValueFactory(new PropertyValueFactory<>("Remark"));
                ISBN.setPrefWidth(100);Name.setPrefWidth(200);Author.setPrefWidth(100);
                Press.setPrefWidth(150);Price.setPrefWidth(100);Number.setPrefWidth(100);
                Location.setPrefWidth(200);Label.setPrefWidth(150);Remark.setPrefWidth(100);

                tableViewBook.getColumns().addAll(ISBN, Name, Author, Press, Price, Number, Location, Label, Remark);
                ObservableList<Book> BookList =
                        FXCollections.observableArrayList(books);
                tableViewBook.setItems(BookList);
                //不同功能区的可操作按钮布局
                if(choose==1|choose==3|choose==9)ButtonBox.getChildren().addAll(Back, Confirm, Cancel);
                else ButtonBox.getChildren().addAll(Back,Initial, Change, Delete, Cancel);
                Layout.getChildren().addAll(tableViewBook, ButtonBox);

                //通过command进行实际操作控制
                command.set(1);
                tableViewBook.addEventHandler (MouseEvent.MOUSE_CLICKED, event -> {
                    int time = event.getClickCount();
                    if(time==2&tableViewBook.getItems().size()!=0){
                        String[] SelectBookStr = tableViewBook.getFocusModel().getFocusedItem()
                                .toString().split(",", -1);
                        Book SelectBook = new Book(
                                SelectBookStr[0],SelectBookStr[1],SelectBookStr[2],SelectBookStr[3],
                                Integer.parseInt(SelectBookStr[4]),Double.valueOf(SelectBookStr[5]),
                                SelectBookStr[6],SelectBookStr[7], SelectBookStr[8]
                        );
                        //初始
                        if(command.get() ==1) {
                            for (int i = 0; i < books.size(); i++) {
                                if (books.get(i).getISBN().equals(SelectBook.getISBN())) {
                                    if (books.get(i).getNumber() > 1)
                                        books.get(i).setNumber(books.get(i).getNumber() - 1);
                                    else books.remove(i);
                                    break;
                                }
                            }
                        }
                        //修改
                        else if(command.get() ==2){
                            ChangeUI changeUI = new ChangeUI();
                            changeUI.display(new Stage(), 1, SelectBook);
                        }
                        //删除
                        else if(command.get()==3){
                            try {
                                SelectBook.setNumber(SelectBook.getStock());
                                bookDao.deleteBook(SelectBook);
                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                alert.setTitle("提示");
                                alert.setHeaderText("你所选已删除");
                                alert.initStyle(StageStyle.UTILITY);//不显示图标
                                alert.show();
                            } catch (DaoException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        //数据修改后进行当前表单展示数据修改
                        UpdateTableDate(tableViewBook, books, 1);
                    }
                });
                Initial.setOnMouseClicked(e-> command.set(1));
                Change.setOnMouseClicked(e-> command.set(2));
                Delete.setOnMouseClicked(e->command.set(3));
                Cancel.setOnMouseClicked(event -> {
                    books.clear();
                    UpdateTableDate(tableViewBook, books, 1);
                });

                if(choose==1){
                    Confirm.setOnMouseClicked(e->{
                        if(books.size()!=0){
                            for (Book book: books) {
                                Calendar calendar = Calendar.getInstance();
                                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                Date date = calendar.getTime();
                                LocalDateTime localDateTime = date.toInstant()
                                        .atZone(ZoneId.systemDefault())
                                        .toLocalDateTime().plusMonths(1);
                                date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
                                Record record = new Record(
                                        0, user.getNumber(), null, book.getISBN(), null,
                                        book.getNumber(), dateFormat.format(calendar.getTime()), dateFormat.format(date),
                                        null, "借阅中"
                                );
                                try {
                                    recordDao.addRecord(record);
                                    bookDao.deleteBook(book);
                                } catch (DaoException ex) {
                                    ex.printStackTrace();
                                }
                            }
                            books.clear();
                            UpdateTableDate(tableViewBook, books, 1);
                            ManagerUI.UpdateWindows(ManagerUI.rootNode);
                        }
                    });
                }
                else if(choose==3){
                    Confirm.setOnMouseClicked(e->{
                        if(books.size()!=0){
                            for (Book book: books) {
                                Calendar calendar = Calendar.getInstance();
                                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                Bill bill = new Bill(
                                        0, book.getName(), book.getAuthor(), user.getNumber(),
                                        user.getName(), book.getNumber(), book.getPrice(),
                                        dateFormat.format(calendar.getTime())
                                );
                                bill.setISBN(book.getISBN());
                                try {
                                    billDao.addBill(bill);
                                    bookDao.deleteBook(book);
                                } catch (DaoException ex) {
                                    ex.printStackTrace();
                                }
                            }
                            books.clear();
                            UpdateTableDate(tableViewBook, books, 1);
                            ManagerUI.UpdateWindows(ManagerUI.rootNode);
                        }
                    });
                }
                else if(choose==9){
                    Confirm.setOnMouseClicked(e->{
                        int count = 0;
                        try {
                            count = bookDao.addBook(books);
                        } catch (DaoException ignored) {

                        }
                        finally {
                            Alert alert = new Alert(Alert.AlertType.INFORMATION);
                            alert.setTitle("提示");
                            alert.setHeaderText("您本次文件共加入"+count+"条记录");
                            alert.initStyle(StageStyle.UTILITY);//不显示图标
                            alert.show();
                        }
                    });
                }
                break;
            case 7:
                TableColumn UserNumber = new TableColumn("账号");
                TableColumn UserName = new TableColumn("姓名");
                TableColumn UserSexy = new TableColumn("性别");
                TableColumn UserClass = new TableColumn("班级");
                TableColumn UserTitle = new TableColumn("职称");
                TableColumn UserFaction = new TableColumn("系别");
                TableColumn UserGrade = new TableColumn("权限");
                UserNumber.setCellValueFactory(new PropertyValueFactory<>("Number"));
                UserName.setCellValueFactory(new PropertyValueFactory<>("Name"));
                UserSexy.setCellValueFactory(new PropertyValueFactory<>("Sexy"));
                UserClass.setCellValueFactory(new PropertyValueFactory<>("discipline"));
                UserTitle.setCellValueFactory(new PropertyValueFactory<>("Title"));
                UserFaction.setCellValueFactory(new PropertyValueFactory<>("Faction"));
                UserGrade.setCellValueFactory(new PropertyValueFactory<>("Grade"));
                UserNumber.setPrefWidth(200);UserName.setPrefWidth(200);
                UserSexy.setPrefWidth(150);UserClass.setPrefWidth(150);
                UserTitle.setPrefWidth(100);UserFaction.setPrefWidth(150);
                UserGrade.setPrefWidth(100);
                tableViewAccount.getColumns().addAll(UserNumber, UserName, UserSexy,
                        UserClass, UserTitle, UserFaction, UserGrade);

                ButtonBox.getChildren().addAll(Back,Initial, Change, Delete, Cancel);

                ObservableList<User> UserList =
                        FXCollections.observableArrayList(accounts);
                tableViewAccount.setItems(UserList);
                Layout.getChildren().addAll(tableViewAccount, ButtonBox);

                command.set(1);
                tableViewAccount.addEventHandler (MouseEvent.MOUSE_CLICKED, event -> {
                    int time = event.getClickCount();
                    if(time==2&tableViewAccount.getItems().size()!=0){
                        String[] SelectAccountStr = tableViewAccount.getFocusModel().getFocusedItem()
                                .toString().split(",", -1);
                        User SelectUser = new User(
                                SelectAccountStr[0],SelectAccountStr[1],SelectAccountStr[2],
                                SelectAccountStr[3], SelectAccountStr[4],SelectAccountStr[5],
                                SelectAccountStr[6],SelectAccountStr[7]
                        );
                        //初始
                        if(command.get() ==1) {
                            for (int i = 0; i < accounts.size(); i++) {
                                if (accounts.get(i).getNumber().equals(SelectUser.getNumber())) {
                                    accounts.remove(i);
                                    break;
                                }
                            }
                        }
                        //修改
                        else if(command.get() ==2){
                            ChangeUI changeUI = new ChangeUI();
                            changeUI.display(new Stage(), 2, SelectUser);
                        }
                        //删除
                        else if(command.get()==3){
                            try{
                                userDao.deleteAccount(SelectUser);
                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                alert.setTitle("提示");
                                alert.setHeaderText("你所选已删除");
                                alert.initStyle(StageStyle.UTILITY);//不显示图标
                                alert.show();
                            } catch (DaoException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        UpdateTableDate(tableViewAccount, accounts, 2);
                    }
                });
                Initial.setOnMouseClicked(e-> command.set(1));
                Change.setOnMouseClicked(e-> command.set(2));
                Delete.setOnMouseClicked(e->command.set(3));
                Cancel.setOnMouseClicked(event -> {
                    ArrayList<Bill> UsersList = new ArrayList<>();
                    UpdateTableDate(tableViewAccount, UsersList, 2);
                });
                break;
            case 8:
                TableColumn Id = new TableColumn("ID");
                TableColumn BillBookName = new TableColumn("书名");
                TableColumn BillAuthor = new TableColumn("作者");
                TableColumn Account = new TableColumn("账号");
                TableColumn BillAccountName = new TableColumn("姓名");
                TableColumn BillNumber = new TableColumn("数量");
                TableColumn BillPrice = new TableColumn("价格");
                TableColumn Date = new TableColumn("时间");
                Id.setCellValueFactory(new PropertyValueFactory<>("Id"));
                BillBookName.setCellValueFactory(new PropertyValueFactory<>("BookName"));
                BillAuthor.setCellValueFactory(new PropertyValueFactory<>("Author"));
                Account.setCellValueFactory(new PropertyValueFactory<>("Account"));
                BillAccountName.setCellValueFactory(new PropertyValueFactory<>("AccountName"));
                BillNumber.setCellValueFactory(new PropertyValueFactory<>("Number"));
                BillPrice.setCellValueFactory(new PropertyValueFactory<>("Price"));
                Date.setCellValueFactory(new PropertyValueFactory<>("Date"));
                Id.setPrefWidth(100);BillBookName.setPrefWidth(200);
                BillAuthor.setPrefWidth(200);Account.setPrefWidth(150);
                BillAccountName.setPrefWidth(150);BillNumber.setPrefWidth(150);BillPrice.setPrefWidth(150);
                tableViewBill.getColumns().addAll(Id, BillBookName, BillAuthor, Account,
                        BillAccountName, BillNumber, BillPrice, Date);

                ButtonBox.getChildren().addAll(Back, Initial, Delete, Cancel);

                ObservableList<Bill> BillList =
                        FXCollections.observableArrayList(bills);
                tableViewBill.setItems(BillList);
                Layout.getChildren().addAll(tableViewBill, ButtonBox);

                command.set(1);
                tableViewBill.addEventHandler (MouseEvent.MOUSE_CLICKED, event -> {
                    int time = event.getClickCount();
                    if(time==2&tableViewBill.getItems().size()!=0){
                        String[] SelectBillStr = tableViewBill.getFocusModel().getFocusedItem()
                                .toString().split(",", -1);
                        Bill SelectBill = new Bill(
                                Integer.parseInt(SelectBillStr[0]),SelectBillStr[1],SelectBillStr[2],
                                SelectBillStr[3],SelectBillStr[4],Integer.parseInt(SelectBillStr[5]),
                                Double.valueOf(SelectBillStr[6]),SelectBillStr[7]
                        );
                        //初始
                        if(command.get() ==1) {
                            for (int i = 0; i < bills.size(); i++) {
                                if (bills.get(i).getId() == SelectBill.getId()) {
                                    bills.remove(i);
                                    break;
                                }
                            }
                        }
                        //删除
                        else if(command.get()==2){
                            try{
                                billDao.deleteBill(SelectBill);
                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                alert.setTitle("提示");
                                alert.setHeaderText("你所选已删除");
                                alert.initStyle(StageStyle.UTILITY);//不显示图标
                                alert.show();
                            } catch (DaoException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        UpdateTableDate(tableViewBill, bills, 5);
                    }
                });
                Initial.setOnMouseClicked(e-> command.set(1));
                Delete.setOnMouseClicked(e->command.set(2));
                Cancel.setOnMouseClicked(event -> {
                    ArrayList<Bill> BillsList = new ArrayList<>();
                    UpdateTableDate(tableViewBill, BillsList, 5);
                });
                break;
            default:
        }
        Back.setOnMouseClicked(event -> settlement.hide());

        settlement.setOnCloseRequest(event -> ManagerUI.UpdateWindows(ManagerUI.rootNode));

        Layout.setAlignment(Pos.CENTER);
        Layout.setSpacing(10);
        settlement.setTitle(this.name);
        settlement.setResizable(false);
        settlement.setScene(scene);
        settlement.getIcons().add(new Image("fodder/控制台.png"));
        settlement.initModality(Modality.APPLICATION_MODAL);
        settlement.showAndWait();
    }
    public static void UpdateTableDate(TableView tableView, ArrayList arrayList, int choose){
        //更新当前界面的数据
        //参数:
        //tableView:需要进行更新展示的表格控件
        //arrayList:需要进行被更新展示的数据
        //choose:控制值
        int MaxLen= arrayList.size();
        switch (choose){
            case 1:
            case 3:
            case 6:
                Book[] books = (Book[]) arrayList.subList(0,MaxLen).toArray(new Book[0]);
                ObservableList<Book> SelectBook = FXCollections.observableArrayList(books);
                ((TableView<Book>) tableView).setItems(SelectBook);
                break;
            case 2:
                User[] accounts = (User[]) arrayList.subList(0,MaxLen).toArray(new User[0]);
                ObservableList<User> SelectAccount = FXCollections.observableArrayList(accounts);
                ((TableView<User>) tableView).setItems(SelectAccount);
                break;
            case 5:
                Bill[] bills = (Bill[]) arrayList.subList(0, MaxLen).toArray(new Bill[0]);
                ObservableList<Bill> SelectBill = FXCollections.observableArrayList(bills);
                ((TableView<Bill>) tableView).setItems(SelectBill);
                break;
        }
    }
}
